package fr.cephb.locustree;

import java.io.IOException;
import java.io.Serializable;
import java.util.Map;

import com.sleepycat.bind.tuple.TupleBinding;
import com.sleepycat.bind.tuple.TupleInput;
import com.sleepycat.bind.tuple.TupleOutput;

import fr.cephb.berkeleydb.binding.JSONBinding;
import fr.cephb.json.JSONBuilder;
import fr.cephb.json.JSONable;

/**
 * 
 * Organism
 *
 */
public class Organism
	implements JSONable,Serializable,Comparable<Organism>
	{
	private static final long serialVersionUID = 1L;
	
	private Integer id;
	private String name;
	private String description;
	private Map<String,Object> json=null;
	
	public static class Binding
		extends TupleBinding<Organism>
		{
		private JSONBinding jsonBinding=new JSONBinding();
		@SuppressWarnings("unchecked")
		@Override
		public Organism entryToObject(TupleInput in)
			{
			Organism o= new Organism(in.readInt(),in.readString());
			o.setDescription(in.readString());
			o.setObject((Map<String,Object>)jsonBinding.entryToObject(in));
			return o;
			}
		@Override
		public void objectToEntry(Organism o, TupleOutput out)
			{
			out.writeInt(o.getId()).
				writeString(o.getName()).
				writeString(o.getDescription())
				;
			jsonBinding.objectToEntry(o.getObject(), out);
			}
		}
	
	public Organism(Integer id,String name)
		{
		super();
		this.id=id;
		this.description=name;
		this.name = name;
		}
	
	@Override
	public int compareTo(Organism o)
		{
		return getName().compareToIgnoreCase(o.getName());
		}
	
	@Override
	public int hashCode()
		{
		final int prime = 31;
		int result = 1;
		result = prime * result + id.hashCode();
		return result;
		}

	@Override
	public boolean equals(Object obj)
		{
		if (this == obj) return true;
		if (obj == null) return false;
		if (getClass() != obj.getClass()) return false;
		Organism other = (Organism) obj;
		if (!id.equals(other.id)) return false;
		return true;
		}
	
	public Integer getId()
		{
		return id;
		}

	public Map<String,Object> getObject()
		{
		return json;
		}
	public void setObject(Map<String,Object> json)
		{
		this.json = json;
		}
	

	public String getName()
		{
		return name;
		}
	
	public void setDescription(String description)
		{
		this.description = description;
		}

	public String getDescription()
		{
		return description==null?getName():description;
		}
	
	public String getMetadataAsJson() throws IOException
		{
		return new JSONBuilder().toString(getObject());
		}
	
	@Override
	public String toJSON()
		{
		return new JSONBuilder().
			put("id", getId()).
			put("name", getName()).
			put("metadata", getObject()).
			put("description", getDescription()).
			getString();
		}
	
	@Override
	public String toString()
		{
		return toJSON();
		}
	}
